<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-select style="width: 190px" clearable class="filter-item" v-model="whereQuery.groupId" filterable placeholder="列表组" @change="handleFilter">
        <el-option v-for="item in groupOptions" :key="item._id" :label="item.name" :value="item._id">
        </el-option>
      </el-select>
      <el-select clearable style="width: 130px" class="filter-item" v-model="whereQuery.type" placeholder="种类" @change="handleFilter">
        <el-option v-for="item in listTypeOptions" :key="item" :label="item | listTypeFilter" :value="item">
        </el-option>
      </el-select>
      <el-select clearable style="width: 110px" class="filter-item" v-model="whereQuery.createdType" placeholder="创建方式" @change="handleFilter">
        <el-option v-for="item in createdTypeOptions" :key="item" :label="item | createdTypeFilter" :value="item">
        </el-option>
      </el-select>
      <el-select clearable style="width: 110px" class="filter-item" v-model="whereQuery.visible" placeholder="是否展示" @change="handleFilter">
        <el-option v-for="item in booleanOptions" :key="item.key" :label="item.value" :value="item.key">
        </el-option>
      </el-select>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">添加</el-button>
    </div>

    <el-table :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row
              style="width: 100%">
      <el-table-column align="center" label="id" width="300">
        <template slot-scope="scope">
          <span class="link-type" style="font-family: Menlo, Monaco, Consolas, Courier New, monospace;" @click="showJsonObject(scope.row)">{{scope.row._id}}</span>
        </template>
      </el-table-column>
      <el-table-column width="135px" align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{scope.row.createdAt | momentFormat('YYYY-MM-DD HH:mm')}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="100px" header-align="center" label="名称" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column width="110px" align="center" label="种类">
        <template slot-scope="scope">
          <span>{{scope.row.type | listTypeFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column width="80px" align="center" label="排序">
        <template slot-scope="scope">
          <span>{{scope.row.index}}</span>
        </template>
      </el-table-column>
      <el-table-column width="120px" header-align="center" label="列表组" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="link-type" v-if="scope.row.group" @click="showJsonObject(scope.row.group)">{{scope.row.group.name}}</span>
        </template>
      </el-table-column>
      <el-table-column width="100px" header-align="center" label="主体" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="link-type" v-if="scope.row.body" @click="showJsonObject(scope.row.body)">{{scope.row.body.name}}</span>
        </template>
      </el-table-column>
      <el-table-column width="100px" header-align="center" label="网页" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="link-type" v-if="scope.row.value" @click="openWindow(scope.row.value)">{{scope.row.value}}</span>
        </template>
      </el-table-column>
      <el-table-column width="80px" align="center" label="封面">
        <template slot-scope="scope" v-if="scope.row.cover && scope.row.cover.url">
          <el-popover ref="coverPopover" placement="top" width="220" trigger="hover">
            <el-form>
              <el-form-item min-width="200">
                <img :src="scope.row.cover.url+'?imageView2/2/w/200/h/200'" class="avatar">
              </el-form-item>
            </el-form>
          </el-popover>
          <el-button v-popover:coverPopover type="text"  @click="openWindow(scope.row.cover.url)">cover</el-button>
        </template>
      </el-table-column>
      <el-table-column width="50px" label="展示">
        <template slot-scope="scope">
          <span v-if="scope.row.visible">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="150" class-name="small-padding" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="success" v-bind:disabled="!scope.row.group || scope.row.group.type === 2" @click="handleUpdate(scope.row)">编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <el-dialog title="对象" :visible.sync="jsonVisible">
      <el-form label-position="right" style='min-width: 600px;'>
        <el-form-item>
          <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 27}" v-model="jsonObject">
          </el-input>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="120px" style='width: 550px; margin-left:50px;'>
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select class="filter-item" v-model="temp.type" placeholder="请选择" @change="handleChangeType" v-bind:disabled="temp._id != undefined">
            <el-option v-for="item in listTypeOptions" :key="item" :label="item | listTypeFilter" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主体(id)" v-show="temp.type === 1 || temp.type === 2 || temp.type === 4">
          <el-input v-model="temp.body._id"></el-input>
        </el-form-item>
        <el-form-item label="网页地址" v-show="temp.type === 3">
          <el-input v-model="temp.value"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="index" :rules="[{pattern: /^\d*$/,message: '排序只能输入整数值'}]">
          <el-input v-model.number="temp.index"></el-input>
        </el-form-item>
        <el-form-item label="列表组(id)">
          <el-col :span="16">
            <el-input style="width: 100%" v-model="temp.group._id"></el-input>
          </el-col>
          <el-col class="line" :span="1">-</el-col>
          <el-col :span="7">
            <el-select style="width: 100%;" clearable v-model="temp.group._id" filterable placeholder="可选择">
              <el-option v-for="item in groupOptions" :disabled="item.type != 1" :key="item._id" :label="item.name" :value="item._id">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="是否展示">
          <el-select class="filter-item" v-model="temp.visible" placeholder="请选择">
            <el-option v-for="item in booleanOptions" :key="item.key" :label="item.value" :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="封面图">
          <el-upload action="https://upload-z1.qbox.me" accept="image/*" :on-success = 'afterUpload' :data="dataObj" drag :multiple="false" :before-upload="beforeUpload" :show-file-list="false">
            <img v-if="coverUrl" :src="temp.cover.url+'?imageView2/2/w/200/h/200'" class="avatar">
            <div v-else>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </div>
          </el-upload>
          <div class="el-upload__tip">请上传png、jpg及jpeg格式图片(大小2M以下,建议分辨率 xx * xx)</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确 定</el-button>
        <el-button v-else type="primary" @click="updateData">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { fetch, insert, deleteById, update } from '@/api/jb'
  import { getToken } from '@/api/qiniu'
  import waves from '@/directive/waves' // 水波纹指令
  import { MessageBox } from 'element-ui'

  const booleanOptions = [
    { key: true, value: '是' },
    { key: false, value: '否' }
  ]

  export default {
    name: 'storeList',
    directives: {
      waves
    },
    data() {
      return {
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          skip: 0,
          limit: 10,
          include: 'body,group',
          where: {
            group: {
              __type: 'Pointer',
              className: 'ListGroup',
              _id: undefined
            },
            createdType: 2,
            type: undefined,
            visible: undefined
          },
          count: true,
          order: {
            createdAt: -1
          }
        },
        listGroupQuery: {
          skip: 0,
          limit: 100,
          keys: ['_id', 'name'],
          order: {
            updateAt: -1
          }
        },
        whereQuery: {
          groupId: undefined,
          type: undefined,
          createdType: 2,
          visible: undefined
        },
        groupOptions: [],
        listTypeOptions: [1, 2, 3, 4],
        createdTypeOptions: [1, 2],
        booleanOptions,
        sortOptions: [{ label: '按ID升序列', key: '+id' }, { label: '按ID降序', key: '-id' }],
        temp: {
          _id: undefined,
          name: undefined,
          type: 1,
          index: 0,
          group: {
            _id: undefined,
            __type: 'Pointer',
            className: 'ListGroup'
          },
          createdType: undefined,
          body: {
            _id: undefined,
            __type: 'Pointer',
            className: undefined
          },
          value: undefined,
          visible: false,
          cover: {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          }
        },
        dialogFormVisible: false,
        jsonVisible: false,
        jsonObject: undefined,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        dataObj: { token: '', key: '' },
        coverUrl: undefined,
        qiniuParams: {
          fileName: 'storeList',
          platform: 'qiniu'
        },
        rules: {
          // name: [{ required: true, message: '列表名称不能为空', trigger: 'change' }],
          type: [{ required: true, message: '类型 is required', trigger: 'change' }]
        }
      }
    },
    filters: {
      listTypeFilter(type) {
        const listType = ['应用', '列表', '网页', '分类/标签']
        return type > 0 ? listType[type - 1] : ''
      },
      createdTypeFilter(type) {
        const createdType = ['定时刷新', '手动添加']
        return type > 0 ? createdType[type - 1] : ''
      },
      json: (value) => { return JSON.stringify(value, null, 2) }
    },
    created() {
      this.getList()
      fetch('ListGroup', this.listGroupQuery).then(response => {
        this.groupOptions = response.data.data.result
      })
    },
    methods: {
      getList() {
        this.listLoading = true
        if (this.whereQuery.groupId) {
          this.listQuery.where.group = {
            __type: 'Pointer',
            className: 'ListGroup',
            _id: this.whereQuery.groupId
          }
        } else {
          this.listQuery.where.group = undefined
        }
        if (this.whereQuery.type) {
          this.listQuery.where.type = this.whereQuery.type
        } else {
          this.listQuery.where.type = undefined
        }
        if (this.whereQuery.createdType) {
          this.listQuery.where.createdType = this.whereQuery.createdType
        } else {
          this.listQuery.where.createdType = undefined
        }
        if (this.whereQuery.visible === '') {
          this.listQuery.where.visible = undefined
        } else {
          this.listQuery.where.visible = this.whereQuery.visible
        }
        fetch('StoreList', this.listQuery).then(response => {
          this.list = response.data.data.result
          this.total = response.data.data.count
          this.listLoading = false
        })
      },
      handleFilter() {
        this.listQuery.skip = 0
        this.getList()
      },
      handleSizeChange(val) {
        this.listQuery.limit = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.skip = (val - 1) * this.listQuery.limit
        this.getList()
      },
      resetTemp() {
        this.temp = {
          _id: undefined,
          name: undefined,
          type: 1,
          index: 0,
          group: {
            _id: undefined,
            __type: 'Pointer',
            className: 'ListGroup'
          },
          createdType: undefined,
          body: {
            _id: undefined,
            __type: 'Pointer',
            className: undefined
          },
          value: undefined,
          visible: false,
          cover: {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          }
        }
      },
      handleChangeType(type) {
        if (type === 3) {
          this.temp.body._id = undefined
        } else {
          this.temp.value = undefined
        }
      },
      beforeUpload() {
        // this.temp.cover._id = undefined
        const _self = this
        return new Promise((resolve, reject) => {
          getToken(this.qiniuParams).then(response => {
            const key = response.data.data.name
            const token = response.data.data.token
            _self._data.dataObj.token = token
            _self._data.dataObj.key = key
            resolve(true)
          }).catch(err => {
            console.log(err)
            reject(false)
          })
        })
      },
      afterUpload(res) {
        this.temp.cover._id = res.data.file._id
        this.temp.cover.url = res.data.file.url
        this.coverUrl = res.data.file.url
      },
      handleCreate() {
        this.resetTemp()
        this.temp.createdType = 2
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.dataObj = {}
        this.coverUrl = undefined
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            if (!this.temp.group._id) {
              tempData.group = undefined
            }
            if (!this.temp.cover._id) {
              tempData.cover = undefined
            }
            if (this.temp.body._id) {
              tempData.body.className = this.getClassName(this.temp.type)
            } else {
              tempData.body = undefined
            }
            insert('StoreList', tempData).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
              this.listQuery.skip = 0
              this.getList()
            })
          }
        })
      },
      handleUpdate(row) {
        for (const key of Reflect.ownKeys(this.temp)) {
          this.temp[key] = row[key]
        }
        if (!this.temp.cover) {
          this.temp.cover = {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          }
        } else {
          this.coverUrl = this.temp.cover.url
        }
        if (!this.temp.group) {
          this.temp.group = {
            _id: undefined,
            __type: 'Pointer',
            className: 'ListGroup'
          }
        }
        if (!this.temp.body) {
          this.temp.body = {
            _id: undefined,
            __type: 'Pointer',
            className: this.getClassName(this.temp.type)
          }
        }
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      getClassName(type) {
        if (type === 1) {
          return 'App'
        } else if (type === 2) {
          return 'ListGroup'
        } else if (type === 4) {
          return 'Tag'
        } else {
          return undefined
        }
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            if (!this.temp.group || !this.temp.group._id) {
              tempData.group = undefined
            }
            if (!this.temp.cover || !this.temp.cover._id) {
              tempData.cover = undefined
            }
            if (!this.temp.body || !this.temp.body._id) {
              tempData.body = undefined
            }

            update('StoreList', this.temp._id, tempData).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            })
          }
        })
      },
      handleDelete(row) {
        MessageBox.confirm('是否确认删除？', '确定删除', {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteById('StoreList', row._id).then(response => {
            if (response.data.code === 0) {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
              const index = this.list.indexOf(row)
              this.list.splice(index, 1)
            } else {
              this.$notify({
                title: '失败',
                message: response.data.message,
                type: 'info',
                duration: 2000
              })
            }
          })
        })
      },
      showJsonObject(data) {
        this.jsonVisible = true
        this.jsonObject = JSON.stringify(data, null, 4)
      },
      openWindow(value) {
        window.open(value)
      }
    }
  }
</script>
<style scoped>

</style>
